package com.example.myservlet;

import com.example.anno.RequestMapping;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/caffe")
public class CaffeineTestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
//        test1();
        testIfPresent();
    }

    private void test1() {
        Cache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100) // 最大缓存条目数
                .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
                .build();

        cache.put("name", "Alice");
        String value = cache.getIfPresent("name");
        log.info(value); // 输出 Alice
    }

    private void testIfPresent() {
        LoadingCache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100)
                .build(key -> loadFromDatabase(key));

        String value = cache.get("user123"); // 如果缓存中没有，会调用 loadFromDatabase
        log.info(value);
    }

    private static String loadFromDatabase(String key) {
        // 模拟从数据库加载
        return "UserData for " + key;
    }
}